import React, { useState } from 'react';
import { Button, Tooltip, Space, Dropdown, MenuProps } from 'antd';
import { 
  BoldOutlined, 
  ItalicOutlined, 
  UnderlineOutlined, 
  OrderedListOutlined, 
  UnorderedListOutlined, 
  LinkOutlined, 
  PictureOutlined, 
  CodeOutlined,
  AlignLeftOutlined,
  AlignCenterOutlined,
  AlignRightOutlined,
  TableOutlined
} from '@ant-design/icons';
import styled from 'styled-components';

interface MarkdownEditorProps {
  value: string;
  onChange: (value: string) => void;
  isDarkMode: boolean;
}

const EditorContainer = styled.div`
  height: 100%;
  display: flex;
  flex-direction: column;
`;

const ToolbarContainer = styled.div`
  padding: 8px;
  border-bottom: 1px solid #f0f0f0;
  background-color: ${props => props.theme.isDark ? '#1f1f1f' : '#fff'};
`;

const MarkdownInput = styled.textarea`
  width: 100%;
  height: 100%;
  border: none;
  resize: none;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  padding: 16px;
  background-color: ${props => props.theme.isDark ? '#1f1f1f' : '#fff'};
  color: ${props => props.theme.isDark ? '#f0f0f0' : '#000'};
  &:focus {
    outline: none;
  }
`;

const MarkdownEditor: React.FC<MarkdownEditorProps> = ({ value, onChange, isDarkMode }) => {
  const [selectionStart, setSelectionStart] = useState<number>(0);
  const [selectionEnd, setSelectionEnd] = useState<number>(0);
  
  // Track textarea selection
  const handleSelect = (e: React.SyntheticEvent<HTMLTextAreaElement>) => {
    const target = e.target as HTMLTextAreaElement;
    setSelectionStart(target.selectionStart);
    setSelectionEnd(target.selectionEnd);
  };
  
  // Insert markdown syntax at cursor position or around selected text
  const insertMarkdown = (before: string, after: string = '') => {
    const newValue = 
      value.substring(0, selectionStart) + 
      before + 
      value.substring(selectionStart, selectionEnd) + 
      after + 
      value.substring(selectionEnd);
    
    onChange(newValue);
  };
  
  // Format functions
  const formatBold = () => insertMarkdown('**', '**');
  const formatItalic = () => insertMarkdown('*', '*');
  const formatUnderline = () => insertMarkdown('<u>', '</u>');
  const formatOrderedList = () => insertMarkdown('1. ');
  const formatUnorderedList = () => insertMarkdown('- ');
  
  const formatLink = () => {
    const selectedText = value.substring(selectionStart, selectionEnd);
    const url = selectedText.startsWith('http') ? selectedText : 'https://example.com';
    insertMarkdown('[', `](${url})`);
  };
  
  const formatImage = () => {
    insertMarkdown('![图片描述](', ')');
  };
  
  const formatCode = () => {
    const selectedText = value.substring(selectionStart, selectionEnd);
    if (selectedText.includes('\n')) {
      insertMarkdown('```\n', '\n```');
    } else {
      insertMarkdown('`', '`');
    }
  };
  
  const formatTable = () => {
    const tableTemplate = '| 标题1 | 标题2 | 标题3 |\n| --- | --- | --- |\n| 内容1 | 内容2 | 内容3 |\n';
    insertMarkdown(tableTemplate);
  };

  // Heading dropdown menu items
  const headingItems: MenuProps['items'] = [
    { key: '1', label: 'H1', onClick: () => insertMarkdown('# ') },
    { key: '2', label: 'H2', onClick: () => insertMarkdown('## ') },
    { key: '3', label: 'H3', onClick: () => insertMarkdown('### ') },
    { key: '4', label: 'H4', onClick: () => insertMarkdown('#### ') },
    { key: '5', label: 'H5', onClick: () => insertMarkdown('##### ') },
    { key: '6', label: 'H6', onClick: () => insertMarkdown('###### ') },
  ];

  return (
    <EditorContainer>
      <ToolbarContainer theme={{ isDark: isDarkMode }}>
        <Space>
          <Dropdown menu={{ items: headingItems }} placement="bottomLeft">
            <Button>标题</Button>
          </Dropdown>
          
          <Tooltip title="加粗">
            <Button icon={<BoldOutlined />} onClick={formatBold} />
          </Tooltip>
          
          <Tooltip title="斜体">
            <Button icon={<ItalicOutlined />} onClick={formatItalic} />
          </Tooltip>
          
          <Tooltip title="下划线">
            <Button icon={<UnderlineOutlined />} onClick={formatUnderline} />
          </Tooltip>
          
          <Tooltip title="有序列表">
            <Button icon={<OrderedListOutlined />} onClick={formatOrderedList} />
          </Tooltip>
          
          <Tooltip title="无序列表">
            <Button icon={<UnorderedListOutlined />} onClick={formatUnorderedList} />
          </Tooltip>
          
          <Tooltip title="链接">
            <Button icon={<LinkOutlined />} onClick={formatLink} />
          </Tooltip>
          
          <Tooltip title="图片">
            <Button icon={<PictureOutlined />} onClick={formatImage} />
          </Tooltip>
          
          <Tooltip title="代码">
            <Button icon={<CodeOutlined />} onClick={formatCode} />
          </Tooltip>
          
          <Tooltip title="表格">
            <Button icon={<TableOutlined />} onClick={formatTable} />
          </Tooltip>
        </Space>
      </ToolbarContainer>
      
      <MarkdownInput 
        value={value} 
        onChange={(e) => onChange(e.target.value)}
        onSelect={handleSelect}
        placeholder="在此输入Markdown内容..."
        theme={{ isDark: isDarkMode }}
      />
    </EditorContainer>
  );
};

export default MarkdownEditor;
